package com.microframework.boot.visual.controller;

import java.sql.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.microframework.base.core.datasource.annotation.Tx;
import com.microframework.base.core.util.SecurityUtils;
import com.microframework.base.core.util.UuidUtil;
import com.microframework.base.web.resp.R;
import com.microframework.boot.fs.service.IMinioService;
import com.microframework.boot.visual.model.domain.MaterialImage;
import com.microframework.boot.visual.service.IMaterialImageService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/visual/material/image")
@Tag(name = "素材图片管理", description = "素材图片管理相关接口")
public class MaterialImageController {

	@Autowired
	private IMinioService minioService;

	@Autowired
	private IMaterialImageService materialImageService;

	private final String BUCKET_NAME = "visual";

	@Operation(summary = "分页获取素材图片列表")
	@Parameters({ @Parameter(name = "categoryId", description = "分类Id", required = false),
			@Parameter(name = "keywords", description = "关键字", required = false),
			@Parameter(name = "cur", description = "当前页码", required = true),
			@Parameter(name = "limit", description = "每页数据量", required = true) })
	@GetMapping("/pages")
	public R<Page<MaterialImage>> pages(
			@RequestParam(name = "categoryId", required = false, defaultValue = "") String categoryId,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
		return R.ok(materialImageService.pages(categoryId, keywords, cur, limit));
	}

	@Operation(summary = "保存素材图片")
	@Parameters({ @Parameter(name = "thumbnailFile", description = "素材图片", required = false),
			@Parameter(name = "materialImage", description = "素材信息", required = true) })
	@PostMapping("/save")
	@Tx(value = "micro_visual")
	public R<MaterialImage> save(HttpServletRequest request, MultipartFile thumbnailFile, MaterialImage materialImage) {
		try {
			if (StrKit.notBlank(materialImage.getId())) {
				materialImage.setModifyTime(new Date(System.currentTimeMillis()));
				materialImage.setModifyUserId(SecurityUtils.getUserId());
				if (materialImage.update()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, materialImage.getId());
						String ext = minioService.getFileExtension(thumbnailFile);
						materialImage.setType(minioService.determineMediaType(path).getType());
						materialImage.setExt(ext);
						materialImage.setUrl(path + '.' + ext);
						materialImage.update();
					}
					return R.ok(materialImage);
				} else {
					return R.fail("更新失败！");
				}
			} else {
				materialImage.setId(UuidUtil.getUUID());
				materialImage.setCreateTime(new Date(System.currentTimeMillis()));
				materialImage.setCreateUserId(SecurityUtils.getUserId());
				if (materialImage.save()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, materialImage.getId());
						String ext = minioService.getFileExtension(thumbnailFile);
						materialImage.setType(minioService.determineMediaType(path).getType());
						materialImage.setExt(ext);
						materialImage.setUrl(path + '.' + ext);
						materialImage.update();
					}
					return R.ok(materialImage);
				} else {
					return R.fail("保存失败.");
				}
			}
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

	@Operation(summary = "获取素材图片")
	@Parameters({ @Parameter(name = "url", description = "素材图片url", required = true) })
	@GetMapping("/{url}")
	public ResponseEntity<InputStreamResource> getThumbnail(@PathVariable String url) {
		return minioService.getThumbnail(BUCKET_NAME, url);
	}

	@Operation(summary = "删除素材图片")
	@Parameters({ @Parameter(name = "id", description = "素材图片id", required = true) })
	@DeleteMapping("/detain/{id}")
	@Tx
	public R<String> deleteImageById(@PathVariable("id") String id) {
		try {
			MaterialImage materialImage = new MaterialImage();
			materialImage.setId(id);
			materialImage.setIsDel("1");
			if (materialImage.update()) {
				minioService.deleteFile(BUCKET_NAME, id);
				return R.ok("删除成功.");
			} else {
				return R.fail("删除失败.");
			}
		} catch (Exception e) {
			log.error("删除异常:{}", e.getMessage());
			return R.fail(e.getMessage());
		}
	}

}
